#include "Ctrl.h"

#if OperationFactory_

#include <stdlib.h>
#include <stdexcept> // 引入标准异常库  



class Operation
{
private:
    double _numberA = 0;
    double _numberB = 0;
public:
    double GetNumberA() {
        return _numberA;
    }

    void SetNumberA(double value) {
        _numberA = value;
    }

    double GetNumberB() {
        return _numberB;
    }

    void SetNumberB(double value) {
        _numberB = value;
    }

    virtual double GetResult() {
        double result = 0;
        return result;
    }

    virtual ~Operation() = default; // 虚析构函数以确保正确的析构  

    Operation& operator=(const Operation& other) {
        if (this != &other) { // 防止自赋值  
            _numberA = other._numberA; // 将其他对象的值赋给当前对象  
            _numberB = other._numberB; // 将其他对象的值赋给当前对象  

        }
        return *this; // 返回当前对象的引用，以支持链式赋值 
    }

};


class OperationAdd : public Operation
{
public: 
    double  GetResult() override {
        double result = 0;
        result = GetNumberA() + GetNumberB();
        return result;
    }
};

class OperationSub : public Operation
{
public:
    double  GetResult() override {
        double result = 0;
        result = GetNumberA() - GetNumberB();
        return result;
    }
};

class OperationMul : public Operation
{
public:
    double  GetResult() override {
        double result = 0;
        result = GetNumberA() * GetNumberB();
        return result;
    }
};

class OperationDiv : public Operation
{
public:
    double  GetResult() override {
        double result = 0;
        if (GetNumberB() == 0) {
            throw std::invalid_argument("除数不能为0"); // 使用标准异常类型 
        }
        result = GetNumberA() / GetNumberB();
        return result;
    }
};


class OperationFactory {
public:
    static Operation* createOperate(const string& operate) {
        if (operate == "+") {
            return new OperationAdd();
        }
        else if (operate == "-") {
            return new OperationSub();
        }
        else if (operate == "*") {
            return new OperationMul();
        }
        else if (operate == "/") {
            return new OperationDiv();
        }
        return nullptr;
    }
};



int main() {
    OperationFactory* pOF = new OperationFactory();
    Operation* pOperat  =  pOF->createOperate("/");
    pOperat->SetNumberA(1);
    pOperat->SetNumberB(2);
    double result = pOperat->GetResult();
    printf("result = %lf", result);
}

#endif